<template>
  <div class="areabox !w-full">
    <el-select
      v-model="address.province"
      placeholder="请选择省"
      clearable
      @change="handleProvinceSelect"
    >
      <el-option v-for="item in regionData" :label="item.label" :value="item.value" />
    </el-select>
    <el-select
      v-model="address.city"
      clearable
      placeholder="请选择市"
      :disabled="!address.province || cityList.length == 0"
      @change="handleCitySelect"
    >
      <el-option v-for="item in cityList" :label="item.label" :value="item.value" />
    </el-select>
    <el-select
      v-model="address.area"
      clearable
      placeholder="请选择区"
      :disabled="!address.province || !address.city || areaList.length == 0"
      @change="handleAreaSelect"
    >
      <el-option v-for="item in areaList" :label="item.label" :value="item.value" />
    </el-select>
  </div>
  <div class="!w-full mt-2">
    <el-input
      v-noSpace
      v-model="address.location"
      border
      clearable
      placeholder="请输入详细地址"
      :rules="[/^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/g, '请输入正确的地址']"
      :maxlength="60"
      @blur="handleLocationBlur"
    ></el-input>
  </div>
</template>
<script lang="ts" setup>
import { reactive, computed, ComputedRef } from "vue";
import { regionData, codeToText } from "element-china-area-data";

//父组件传递的地址用来回显赋值
const props = defineProps<{
  modelValue?: string;
}>();

//抛出地址
const emit = defineEmits<{
  (
    e: "getAddress",
    data: {
      code: string[]; //区域码
      name: string[]; //汉字
    }
  ): void;
}>();

let address = reactive<{
  province: string;
  city: string;
  area: string;
  location: string;
}>({
  province: "",
  city: "",
  area: "",
  location: "",
});
interface AreaList {
  value: string;
  label: string;
  children?: AreaList[];
}
//切换省份函数
const handleProvinceSelect = () => {
  address.city = "";
  address.area = "";
  address.location = "";
  emit("getAddress", {
    code: [address.province], //区域码
    name: [
      codeToText[address.province],
      codeToText[address.city],
      codeToText[address.area],
      address.location,
    ], //汉字
  });
};
//切换城市函数
const handleCitySelect = () => {
  address.area = "";
  address.location = "";
  emit("getAddress", {
    code: [address.province, address.city], //区域码
    name: [
      codeToText[address.province],
      codeToText[address.city],
      codeToText[address.area],
      address.location,
    ], //汉字
  });
};
//切换地区函数
const handleAreaSelect = () => {
  address.location = "";
  emit("getAddress", {
    code: [address.province, address.city, address.area], //区域码
    name: [
      codeToText[address.province],
      codeToText[address.city],
      codeToText[address.area],
      address.location,
    ], //汉字
  });
};
//详细地址失去焦点
const handleLocationBlur = () => {
  emit("getAddress", {
    code: [address.province, address.city, address.area], //区域码
    name: [
      codeToText[address.province],
      codeToText[address.city],
      codeToText[address.area],
      address.location,
    ], //汉字
  });
};
//二级城市列表
const cityList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  if (!address.province) {
    return [];
  }
  let temp = regionData.find((item: any) => {
    return item.value == address.province;
  });
  return temp?.children ? temp.children : [];
});
//三级地区列表
const areaList: ComputedRef<AreaList[]> = computed((): AreaList[] => {
  if (!address.province || !address.city) {
    return [];
  }
  if (cityList.value.length == 0) {
    return [];
  } else {
    let temp = cityList.value.find((item: any) => {
      return item.value == address.city;
    });
    if (temp) {
      return temp.children ? temp.children : [];
    } else {
      return [];
    }
  }
});
watchEffect(() => {
  if (props.modelValue) {
    const [provinceName, cityName, areaName, location] = props.modelValue.split(",");

    // 省份匹配（直接遍历regionData）
    address.province =
      regionData.find((p) => p.label === provinceName || codeToText[p.value] === provinceName)
        ?.value || "";

    // 城市匹配（基于当前省份数据）
    const cities = regionData.find((p) => p.value === address.province)?.children || [];
    address.city =
      cities.find((c) => c.label === cityName || codeToText[c.value] === cityName)?.value || "";

    // 区县匹配（基于当前城市数据）
    const areas = cities.find((c) => c.value === address.city)?.children || [];
    address.area =
      areas.find((a) => a.label === areaName || codeToText[a.value] === areaName)?.value || "";

    address.location = location || "";
  } else {
    address.province = "";
    address.city = "";
    address.area = "";
    address.location = "";
  }
});
</script>
<style scoped>
.areabox {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 5px;
}
</style>
